import 'package:flutter/material.dart';
import '../../utils/theme_colors.dart';
import 'package:flutter_svg/flutter_svg.dart';

class CharityScreen extends StatefulWidget {
  const CharityScreen({super.key});

  @override
  _CharityScreenState createState() => _CharityScreenState();
}

class _CharityScreenState extends State<CharityScreen> {
  final List<Map<String, dynamic>> _charityProjects = [
    {
      'id': '1',
      'title': '非遗传承人扶持计划',
      'description': '支持贫困地区非遗传承人技艺传承，提供资金和技术支持',
      'targetAmount': 100000.0,
      'currentAmount': 68500.0,
      'donorCount': 234,
      'daysLeft': 15,
      'imageUrl': 'assets/images/charity_heritage.svg',
      'category': '文化传承',
      'organizer': 'HRC基金会',
    },
    {
      'id': '2',
      'title': '乡村非遗工坊建设',
      'description': '在偏远乡村建设非遗工坊，为当地村民提供就业机会',
      'targetAmount': 150000.0,
      'currentAmount': 92300.0,
      'donorCount': 156,
      'daysLeft': 28,
      'imageUrl': 'assets/images/charity_workshop.svg',
      'category': '乡村振兴',
      'organizer': '非遗保护协会',
    },
    {
      'id': '3',
      'title': '非遗文化进校园',
      'description': '推广非遗文化教育，让更多青少年了解和学习传统文化',
      'targetAmount': 80000.0,
      'currentAmount': 45600.0,
      'donorCount': 189,
      'daysLeft': 42,
      'imageUrl': 'assets/images/charity_education.svg',
      'category': '教育公益',
      'organizer': '文化教育基金',
    },
  ];

  final List<Map<String, dynamic>> _myDonations = [
    {
      'projectTitle': '非遗传承人扶持计划',
      'amount': 500.0,
      'date': '2024-01-15',
      'status': '已完成',
    },
    {
      'projectTitle': '乡村非遗工坊建设',
      'amount': 300.0,
      'date': '2024-01-10',
      'status': '已完成',
    },
  ];

  int _selectedTabIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('慈善公益'),
        backgroundColor: ThemeColors.primary,
        elevation: 0,
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, size: 16, color: Colors.white),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.favorite_outline, size: 16, color: Colors.white),
            onPressed: () {
              // 收藏按钮逻辑
            },
          ),
          const SizedBox(width: 8),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            // 统计信息卡片
            _buildStatisticsCard(),
            
            // 标签页切换
            _buildTabBar(),
            
            // 内容区域
            Expanded(
              child: _selectedTabIndex == 0
                  ? _buildCharityProjectsList()
                  : _buildMyDonationsList(),
            ),
          ],
        ),
      ),
    );
  }

  // 统计信息卡片
  Widget _buildStatisticsCard() {
    return Container(
      margin: const EdgeInsets.all(16.0),
      padding: const EdgeInsets.all(20.0),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            ThemeColors.primary,
            ThemeColors.primary.withOpacity(0.8),
          ],
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: ThemeColors.primary.withOpacity(0.3),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            children: [
              Icon(
                Icons.favorite,
                size: 24,
                color: Colors.white,
              ),
              const SizedBox(width: 8),
              Text(
                '我的慈善贡献',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: _buildStatItem('累计捐赠', '¥800', Icons.monetization_on),
              ),
              Expanded(
                child: _buildStatItem('参与项目', '2个', Icons.handshake),
              ),
              Expanded(
                child: _buildStatItem('帮助人数', '156人', Icons.people),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 统计项组件
  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(
          icon,
          size: 20,
          color: Colors.white.withOpacity(0.9),
        ),
        const SizedBox(height: 8),
        Text(
          value,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.white.withOpacity(0.8),
          ),
        ),
      ],
    );
  }

  // 标签页切换
  Widget _buildTabBar() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16.0),
      decoration: BoxDecoration(
        color: const Color(0xFFF5F5F5),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              onTap: () {
                setState(() {
                  _selectedTabIndex = 0;
                });
              },
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 12),
                decoration: BoxDecoration(
                  color: _selectedTabIndex == 0 ? ThemeColors.primary : Colors.transparent,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  '慈善项目',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: _selectedTabIndex == 0 ? Colors.white : ThemeColors.textSecondary,
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: GestureDetector(
              onTap: () {
                setState(() {
                  _selectedTabIndex = 1;
                });
              },
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 12),
                decoration: BoxDecoration(
                  color: _selectedTabIndex == 1 ? ThemeColors.primary : Colors.transparent,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  '我的捐赠',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: _selectedTabIndex == 1 ? Colors.white : ThemeColors.textSecondary,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 慈善项目列表
  Widget _buildCharityProjectsList() {
    return ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemCount: _charityProjects.length,
      itemBuilder: (context, index) {
        final project = _charityProjects[index];
        return _buildCharityProjectCard(project);
      },
    );
  }

  // 慈善项目卡片
  Widget _buildCharityProjectCard(Map<String, dynamic> project) {
    final progress = project['currentAmount'] / project['targetAmount'];
    
    return Container(
      margin: const EdgeInsets.only(bottom: 16.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 项目图片
          Container(
            height: 160,
            decoration: BoxDecoration(
              borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  ThemeColors.primary.withOpacity(0.1),
                  ThemeColors.primary.withOpacity(0.05),
                ],
              ),
            ),
            child: Center(
              child: Icon(
                Icons.favorite_outline,
                size: 48,
                color: ThemeColors.primary,
              ),
            ),
          ),
          
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 项目标题和分类
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        project['title'],
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: ThemeColors.textPrimary,
                        ),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: ThemeColors.primary.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(
                        project['category'],
                        style: TextStyle(
                          fontSize: 12,
                          color: ThemeColors.primary,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ],
                ),
                
                const SizedBox(height: 8),
                
                // 项目描述
                Text(
                  project['description'],
                  style: TextStyle(
                    fontSize: 14,
                    color: ThemeColors.textSecondary,
                    height: 1.4,
                  ),
                ),
                
                const SizedBox(height: 12),
                
                // 进度条
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '已筹集 ¥${project['currentAmount'].toStringAsFixed(0)}',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: ThemeColors.primary,
                          ),
                        ),
                        Text(
                          '目标 ¥${project['targetAmount'].toStringAsFixed(0)}',
                          style: TextStyle(
                            fontSize: 12,
                            color: ThemeColors.textSecondary,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    LinearProgressIndicator(
                      value: progress,
                      backgroundColor: const Color(0xFFF0F0F0),
                      valueColor: AlwaysStoppedAnimation<Color>(ThemeColors.primary),
                      minHeight: 6,
                    ),
                  ],
                ),
                
                const SizedBox(height: 12),
                
                // 项目统计信息
                Row(
                  children: [
                    Icon(
                      Icons.people_outline,
                      size: 16,
                      color: ThemeColors.textSecondary,
                    ),
                    const SizedBox(width: 4),
                    Text(
                      '${project['donorCount']}人参与',
                      style: TextStyle(
                        fontSize: 12,
                        color: ThemeColors.textSecondary,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Icon(
                      Icons.access_time,
                      size: 16,
                      color: ThemeColors.textSecondary,
                    ),
                    const SizedBox(width: 4),
                    Text(
                      '剩余${project['daysLeft']}天',
                      style: TextStyle(
                        fontSize: 12,
                        color: ThemeColors.textSecondary,
                      ),
                    ),
                    const Spacer(),
                    Text(
                      project['organizer'],
                      style: TextStyle(
                        fontSize: 12,
                        color: ThemeColors.textSecondary,
                      ),
                    ),
                  ],
                ),
                
                const SizedBox(height: 16),
                
                // 捐赠按钮
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () {
                      _showDonationDialog(project);
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: ThemeColors.primary,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      elevation: 0,
                    ),
                    child: const Text(
                      '立即捐赠',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 我的捐赠列表
  Widget _buildMyDonationsList() {
    if (_myDonations.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.favorite_border,
              size: 64,
              color: ThemeColors.textSecondary.withOpacity(0.5),
            ),
            const SizedBox(height: 16),
            Text(
              '暂无捐赠记录',
              style: TextStyle(
                fontSize: 16,
                color: ThemeColors.textSecondary,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              '参与慈善项目，传递爱心',
              style: TextStyle(
                fontSize: 14,
                color: ThemeColors.textSecondary.withOpacity(0.7),
              ),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemCount: _myDonations.length,
      itemBuilder: (context, index) {
        final donation = _myDonations[index];
        return _buildDonationHistoryCard(donation);
      },
    );
  }

  // 捐赠历史卡片
  Widget _buildDonationHistoryCard(Map<String, dynamic> donation) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12.0),
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0xFFF0F0F0),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: ThemeColors.primary.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(
              Icons.favorite,
              size: 24,
              color: ThemeColors.primary,
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  donation['projectTitle'],
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: ThemeColors.textPrimary,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  donation['date'],
                  style: TextStyle(
                    fontSize: 12,
                    color: ThemeColors.textSecondary,
                  ),
                ),
              ],
            ),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                '¥${donation['amount'].toStringAsFixed(0)}',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: ThemeColors.primary,
                ),
              ),
              const SizedBox(height: 4),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                decoration: BoxDecoration(
                  color: Colors.green.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  donation['status'],
                  style: TextStyle(
                    fontSize: 10,
                    color: Colors.green,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 显示捐赠对话框
  void _showDonationDialog(Map<String, dynamic> project) {
    final TextEditingController amountController = TextEditingController();
    final List<double> quickAmounts = [50, 100, 200, 500];
    double selectedAmount = 0;

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
              ),
              title: Text(
                '捐赠支持',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: ThemeColors.textPrimary,
                ),
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    project['title'],
                    style: TextStyle(
                      fontSize: 14,
                      color: ThemeColors.textSecondary,
                    ),
                  ),
                  const SizedBox(height: 16),
                  Text(
                    '选择捐赠金额',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: ThemeColors.textPrimary,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Wrap(
                    spacing: 8,
                    children: quickAmounts.map((amount) {
                      final isSelected = selectedAmount == amount;
                      return GestureDetector(
                        onTap: () {
                          setState(() {
                            selectedAmount = amount;
                            amountController.text = amount.toStringAsFixed(0);
                          });
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                          decoration: BoxDecoration(
                            color: isSelected ? ThemeColors.primary : Colors.grey.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(20),
                            border: Border.all(
                              color: isSelected ? ThemeColors.primary : Colors.grey.withOpacity(0.3),
                            ),
                          ),
                          child: Text(
                            '¥${amount.toStringAsFixed(0)}',
                            style: TextStyle(
                              fontSize: 12,
                              color: isSelected ? Colors.white : ThemeColors.textPrimary,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: amountController,
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                      labelText: '自定义金额',
                      prefixText: '¥',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                        borderSide: BorderSide(color: ThemeColors.primary),
                      ),
                    ),
                    onChanged: (value) {
                      setState(() {
                        selectedAmount = double.tryParse(value) ?? 0;
                      });
                    },
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text(
                    '取消',
                    style: TextStyle(color: ThemeColors.textSecondary),
                  ),
                ),
                ElevatedButton(
                  onPressed: selectedAmount > 0 ? () {
                    Navigator.of(context).pop();
                    _processDonation(project, selectedAmount);
                  } : null,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ThemeColors.primary,
                    foregroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text('确认捐赠'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  // 处理捐赠
  void _processDonation(Map<String, dynamic> project, double amount) {
    // 这里可以添加实际的捐赠处理逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('感谢您的爱心捐赠！¥${amount.toStringAsFixed(0)}'),
        backgroundColor: ThemeColors.primary,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
      ),
    );
    
    // 更新本地数据（实际应用中应该调用API）
    setState(() {
      final projectIndex = _charityProjects.indexWhere((p) => p['id'] == project['id']);
      if (projectIndex != -1) {
        _charityProjects[projectIndex]['currentAmount'] += amount;
        _charityProjects[projectIndex]['donorCount'] += 1;
      }
      
      _myDonations.insert(0, {
        'projectTitle': project['title'],
        'amount': amount,
        'date': DateTime.now().toString().substring(0, 10),
        'status': '已完成',
      });
    });
  }
}